<template>
  <div class="pricing-container">
    <!-- 用户订阅信息组件 -->
    <UserSubscriptionInfo class="subscription-info-section" />
    
    <div class="pricing-header">
      <h1>选择适合您的会员方案</h1>
      <p>解锁更多功能，提升您的工作效率</p>
    </div>

    <a-spin :spinning="loading">
      <div class="pricing-plans">
        <a-row :gutter="[24, 24]">
          <a-col :xs="24" :sm="24" :md="8" v-for="(plan, index) in pricingPlans" :key="plan?.id || index">
            <a-card 
              class="pricing-card" 
              :class="{ 'popular': plan?.is_popular }"
              hoverable
            >
              <template #title>
                <div class="plan-title">{{ plan?.name }}</div>
              </template>
              <template #extra v-if="plan?.is_popular">
                <a-tag color="orange">推荐</a-tag>
              </template>
              
              <div class="plan-price">
                <span class="price">¥{{ plan?.price || 0 }}</span>
                <span class="period">/ {{ plan?.duration_months || 1 }}个月</span>
              </div>
              
              <div class="plan-features">
                <ul>
                  <li>
                    <CheckOutlined /> 最多可创建 <strong>{{ plan?.prompt_limit || 0 }}</strong> 个提示词
                  </li>
                  <li v-for="feature in (plan?.features || [])" :key="feature">
                    <CheckOutlined /> {{ feature }}
                  </li>
                </ul>
              </div>
              
              <div class="plan-action">
                <a-button 
                  type="primary" 
                  size="large" 
                  block
                  :disabled="isCurrentPlan(plan)"
                  @click="() => handleSubscribe(plan)"
                >
                  {{ getButtonText(plan) }}
                </a-button>
              </div>
            </a-card>
          </a-col>
        </a-row>
      </div>
    </a-spin>

    <a-modal
      v-model:visible="paymentModalVisible"
      title="确认订阅"
      @ok="confirmSubscription"
      @cancel="paymentModalVisible = false"
      :okButtonProps="{ loading: subscribing }"
      okText="确认支付"
      cancelText="取消"
    >
      <p>您即将订阅 <strong>{{ selectedPlan?.name }}</strong> 方案</p>
      <p>价格: <strong>¥{{ selectedPlan?.price }}</strong></p>
      <p>有效期: <strong>{{ selectedPlan?.duration_months }}个月</strong></p>
      
      <a-divider />
      
      <a-form layout="vertical">
        <a-form-item label="支付方式">
          <a-radio-group v-model:value="paymentMethod">
            <a-radio value="alipay">支付宝</a-radio>
            <a-radio value="wechat">微信支付</a-radio>
          </a-radio-group>
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import { message } from 'ant-design-vue';
import { CheckOutlined } from '@ant-design/icons-vue';
import { useSubscriptionStore } from '../store/subscription';
import { useAuthStore } from '../store/auth';
import UserSubscriptionInfo from '../components/UserSubscriptionInfo.vue';

const router = useRouter();
const subscriptionStore = useSubscriptionStore();
const authStore = useAuthStore();

// 响应式数据
const loading = ref(false);
const pricingPlans = ref([]);
const selectedPlan = ref(null);
const paymentModalVisible = ref(false);
const paymentMethod = ref('alipay');
const subscribing = ref(false);

// 计算属性
const isAuthenticated = computed(() => authStore.isAuthenticated);
const currentSubscription = computed(() => subscriptionStore.currentSubscription);

// 方法定义
const loadPricingPlans = async () => {
  loading.value = true;
  try {
    const plans = await subscriptionStore.fetchPricingPlans();
    pricingPlans.value = plans;
  } catch (error) {
    message.error('获取价格方案失败');
    console.error(error);
  } finally {
    loading.value = false;
  }
};

const loadCurrentSubscription = async () => {
  if (!isAuthenticated.value) return;
  
  try {
    await subscriptionStore.fetchCurrentSubscription();
  } catch (error) {
    console.error('获取当前订阅信息失败:', error);
  }
};

const isCurrentPlan = (plan) => {
  if (!currentSubscription.value) return false;
  return currentSubscription.value.pricing_plan?.id === plan?.id;
};

const getButtonText = (plan) => {
  if (!isAuthenticated.value) {
    return '登录后订阅';
  }
  
  if (isCurrentPlan(plan)) {
    return '当前方案';
  }
  
  return '立即订阅';
};

const handleSubscribe = (plan) => {
  if (!isAuthenticated.value) {
    message.info('请先登录');
    router.push('/auth/login?redirect=/pricing');
    return;
  }
  
  selectedPlan.value = plan;
  paymentModalVisible.value = true;
};

const confirmSubscription = async () => {
  if (!selectedPlan.value) return;
  
  subscribing.value = true;
  try {
    await subscriptionStore.subscribeToNewPlan(selectedPlan.value.id);
    message.success('订阅成功');
    paymentModalVisible.value = false;
    
    // 刷新当前订阅信息
    await loadCurrentSubscription();
  } catch (error) {
    message.error('订阅失败，请稍后重试');
    console.error(error);
  } finally {
    subscribing.value = false;
  }
};

onMounted(() => {
  loadPricingPlans();
  loadCurrentSubscription();
});
</script>

<style scoped>
.pricing-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 2rem;
}

.pricing-header {
  text-align: center;
  margin-bottom: 3rem;
}

.pricing-header h1 {
  font-size: 2.5rem;
  margin-bottom: 1rem;
  color: #1890ff;
  font-weight: 600;
}

.pricing-header p {
  font-size: 1.2rem;
  color: #666;
}

.pricing-plans {
  margin-bottom: 3rem;
}

.pricing-card {
  height: 100%;
  display: flex;
  flex-direction: column;
  transition: transform 0.3s ease;
  border-radius: 8px;
}

.pricing-card:hover {
  transform: translateY(-5px);
}

.pricing-card.popular {
  border-color: #1890ff;
  box-shadow: 0 4px 12px rgba(24, 144, 255, 0.15);
}

.plan-title {
  font-size: 1.5rem;
  font-weight: 600;
  color: #262626;
}

.plan-price {
  text-align: center;
  margin: 1.5rem 0;
}

.plan-price .price {
  font-size: 2.5rem;
  font-weight: 700;
  color: #1890ff;
}

.plan-price .period {
  font-size: 1rem;
  color: #8c8c8c;
  margin-left: 4px;
}

.plan-features {
  margin-bottom: 2rem;
  flex-grow: 1;
}

.plan-features ul {
  list-style: none;
  padding: 0;
  margin: 0;
}

.plan-features li {
  margin-bottom: 1rem;
  display: flex;
  align-items: center;
  color: #595959;
  font-size: 14px;
}

.plan-features li .anticon {
  color: #52c41a;
  margin-right: 8px;
  font-size: 16px;
}

.plan-action {
  margin-top: auto;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .pricing-container {
    padding: 1rem;
  }
  
  .pricing-header h1 {
    font-size: 2rem;
  }
  
  .pricing-header p {
    font-size: 1rem;
  }
  
  .plan-price .price {
    font-size: 2rem;
  }
}
</style>